//
//  JdbcUtil.m
//  LOU
//
//  Created by iMacOne on 15/11/12.
//  Copyright © 2015年 UNOHACHA. All rights reserved.
//

#import "JdbcUtil.h"
#import "General.h"
#import "FileUtil.h"
#import "ToolUtil.h"
#import "DatebaseUtil.h"
#import "DateUtil.h"
#import <sqlite3.h>

static sqlite3 * database = nil;
@implementation JdbcUtil
#pragma mark 根据数据库的名称创建数据库
+ (void)createDatabase:(NSString*)db_name update_db:(void(^)())block
{
    [General shareGeneral].db_path = [FileUtil documentPath:db_name];
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:[General shareGeneral].db_path]) {
        database = [JdbcUtil getDatabase];
        if (block != nil) {
            block();
        }
    }else{
        [manager copyItemAtPath:[FileUtil projectPath:db_name] toPath:[General shareGeneral].db_path error:nil];
        database = [JdbcUtil getDatabase];
        [DatebaseUtil write:key_setup_date value:[DateUtil formatDateTimeStr:[NSDate date]]];
    }
    [DatebaseUtil write:key_version value:[General shareGeneral].version];
    
    
}
#pragma mark 获取数据库连接
+ (sqlite3*)getDatabase
{
    sqlite3 * sqlites = nil;
    if (sqlite3_open([[General shareGeneral].db_path UTF8String], &sqlites) != SQLITE_OK) {
        sqlite3_close(sqlites);
    }
    return sqlites;
}
#pragma mark 获取预编译语句
+ (sqlite3_stmt*)getStatement:(sqlite3*)database sql:(NSString*)sql args:(NSArray*)args
{
    sqlite3_stmt * stmt;
    if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL) == SQLITE_OK) {
        if (args != nil && args.count) {
            for (int i = 0; i < args.count; i++) {
                NSString * arg = (args[i] == nil?@"":args[i]);
                sqlite3_bind_text(stmt, i + 1, [arg UTF8String], -1, SQLITE_TRANSIENT);
            }
        }
        return stmt;
    }
    return nil;
}
#pragma mark 操作数据库,参数必须是字符串数组，也可以为空
+ (BOOL)manage:(NSString*)sql args:(NSArray*)args
{
    sqlite3_stmt * stmt = [JdbcUtil getStatement:database sql:sql  args:args];
    if (stmt == nil) {
        return NO;
    }
    int success = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return  success != SQLITE_ERROR;
}
#pragma mark 查询数据, args必须是字符串数组，也可以为空，keys必须字符串数组，不能为空
+ (NSMutableArray*)getMaps:(NSString*)sql args:(NSArray*)args keys:(NSArray*)keys
{
    NSMutableArray * array = [NSMutableArray array];
    sqlite3_stmt * stmt = [JdbcUtil getStatement:database sql:sql args:args];
    if (stmt == nil) {
        return array;
    }
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        for (int i = 0; i < keys.count; i++) {
            char * value = (char *)sqlite3_column_text(stmt, i);
            NSString * text = (value == NULL? @"":[NSString stringWithUTF8String:value]);
            [dic setValue:text forKey:keys[i]];
        }
        [array addObject:dic];
    }
    sqlite3_finalize(stmt);
    return array;
}
#pragma mark 查询数据, args必须是字符串数组，也可以为空，keys必须字符串数组，不能为空
+ (NSMutableDictionary*)getMap:(NSString*)sql args:(NSArray*)args keys:(NSArray*)keys {
    NSMutableArray *list = [JdbcUtil getMaps:sql args:args keys:keys];
    return (list.count > 0 ? list[0] : nil);
}
#pragma mark 从数据库中获取一列值
+ (NSMutableArray*)getTeam:(NSString*)sql args:(NSArray*)args {
    NSMutableArray *array = [NSMutableArray array];
    sqlite3_stmt *statement = [JdbcUtil getStatement:database sql:sql args:args];
    if (statement == nil) {
        return array;
    }
    while (sqlite3_step(statement) == SQLITE_ROW) {
        char* value = (char*) sqlite3_column_text(statement, 0);
        NSString* text = (value == NULL ? @"" : [NSString stringWithUTF8String:value]);
        [array addObject:text];
    }
    sqlite3_finalize(statement);
    return array;
}
#pragma mark 从数据库中获取一个值
+ (NSString*)getValue:(NSString*)sql args:(NSArray*)args {
    NSMutableArray *list = [JdbcUtil getTeam:sql args:args];
    return (list.count > 0 ? list[0] : @"");
}

#pragma mark 判断真假(数据库中是否有这个纪录)
+ (BOOL)validate:(NSString*)sql args:(NSArray*)args {
    NSString* value = [JdbcUtil getValue:sql args:args];
    if (![ToolUtil isBlank:value] && [value intValue] > 0) {
        return YES;
    }
    return NO;
}
#pragma mark 根据ID删除记录
+ (BOOL)delById:(NSString*)table _id:(int)_id {
    NSString *sql = [NSString stringWithFormat:@"delete from %@ where id = ?", table];
    return [JdbcUtil manage:sql args:@[[NSString stringWithFormat:@"%d", _id]]];
}

@end
